package com.xjtu.project.aop;
import com.xjtu.project.common.utls.SessionUtils;
import com.xjtu.project.mapper.OperateLogMapper;
import com.xjtu.project.model.domain.Log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
public class OperationLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    // 环绕通知
    @Around("@annotation(com.xjtu.project.annotation.LogOperation)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        // 执行方法
        Object result = joinPoint.proceed();
        // 当前时间
        long endTime = System.currentTimeMillis();
        // 耗时
        long costTime = endTime - startTime;

        // 构建日志对象
        Log operateLog = new Log();
        operateLog.setOperateEmpId(SessionUtils.getCurrentEmployeeInfo().getId()); // 需要实现 getCurrentUserId 方法
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        operateLog.setMethodName(joinPoint.getSignature().getName());
        operateLog.setMethodParms(Arrays.toString(joinPoint.getArgs()));
        operateLog.setCostTime(costTime);
        // 插入日志
        operateLogMapper.insert(operateLog);
        return result;
    }
}